//
//  HistoryViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/2.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "HistoryViewController.h"
#import "SubVideoCollectionViewCell.h"
#import "BookCollectionViewCell.h"
#import "MagazineCollectionViewCell.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"

@interface HistoryViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** backScrollView */
@property (nonatomic, strong) UIScrollView * backScrollView;
/** 电子书按钮 */
@property (nonatomic, strong) UIButton * bookButton;
/** 期刊按钮 */
@property (nonatomic, strong) UIButton * magazineButton;
/** 视频按钮 */
@property (nonatomic, strong) UIButton * videoButton;
/** 电子书列表 */
@property (nonatomic, strong) UICollectionView * bookCollectionView;
/** 期刊列表 */
@property (nonatomic, strong) UICollectionView * magazineCollectionView;
/** 视频列表 */
@property (nonatomic, strong) UICollectionView * videoCollectionView;
/** 电子书列表布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * bookFlowLayout;
/** 期刊列表 */
@property (nonatomic, strong) UICollectionViewFlowLayout * magazineFlowLayout;
/** 视频列表布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * videoFlowLayout;
/** 书数据源 */
@property (nonatomic, strong) NSMutableArray * bookArr;
/** 期刊数据源 */
@property (nonatomic, strong) NSMutableArray * magazineArr;
/** 视频数据源 */
@property (nonatomic, strong) NSMutableArray * videoArr;
/** 中间的竖线 */
@property (nonatomic, strong) UIImageView * vLine;
@property (nonatomic, strong) UIImageView * vLine2;
/** 下划线 */
@property (nonatomic, strong) UIImageView * hLine;
/** 视频播放器 */
@property (nonatomic, strong) MPMoviePlayerViewController * player;

@end

@implementation HistoryViewController

#pragma mark - lazy load

- (MPMoviePlayerViewController *)player{
    if (!_player) {
        _player = [[MPMoviePlayerViewController alloc] init];
        _player.moviePlayer.shouldAutoplay = YES;
        _player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;

    }
    return _player;
}

- (NSMutableArray *)videoArr{
    if (!_videoArr) {
        _videoArr = [NSMutableArray array];
    }
    return _videoArr;
}

- (UICollectionViewFlowLayout *)magazineFlowLayout{
    if (!_magazineFlowLayout) {
        _magazineFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _magazineFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _magazineFlowLayout;
}

- (UICollectionView *)magazineCollectionView{
    if (!_magazineCollectionView) {
        _magazineCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREEN_W, 0, SCREEN_W, self.backScrollView.frame.size.height) collectionViewLayout:self.magazineFlowLayout];
        _magazineCollectionView.delegate = self;
        _magazineCollectionView.dataSource = self;
        _magazineCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_magazineCollectionView registerClass:[MagazineCollectionViewCell class] forCellWithReuseIdentifier:@"magazineCell"];
    }
    return _magazineCollectionView;
}

- (UIImageView *)vLine2{
    if (!_vLine2) {
        _vLine2 = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - 2) / 3 * 2, 64 + HeightScale(10), 1, HeightScale(24))];
        _vLine2.image = ImageNamed(@"liulanlishifenge");
    }
    return _vLine2;
}

- (UIButton *)magazineButton{
    if (!_magazineButton) {
        _magazineButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W / 3, 64, SCREEN_W / 3, HeightScale(44))];
        [_magazineButton setTitle:@"期刊" forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _magazineButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_magazineButton initWithBlock:^(id obj) {
            DLog(@"期刊");
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.backScrollView.contentOffset = CGPointMake(SCREEN_W, 0);
                weakSelf.hLine.center = CGPointMake(weakSelf.backScrollView.contentOffset.x / 3 + SCREEN_W / 6, weakSelf.hLine.center.y);
            }];
            
        } for:UIControlEventTouchUpInside];
    }
    return _magazineButton;
}

- (UICollectionViewFlowLayout *)videoFlowLayout{
    if (!_videoFlowLayout) {
        _videoFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _videoFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _videoFlowLayout;
}

- (UICollectionView *)videoCollectionView{
    if (!_videoCollectionView) {
        _videoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREEN_W * 2, 0, SCREEN_W, self.backScrollView.frame.size.height) collectionViewLayout:self.videoFlowLayout];
        _videoCollectionView.delegate = self;
        _videoCollectionView.dataSource = self;
        _videoCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_videoCollectionView registerClass:[SubVideoCollectionViewCell class] forCellWithReuseIdentifier:@"videoCell"];
    }
    return _videoCollectionView;
}

- (UICollectionViewFlowLayout *)bookFlowLayout{
    if (!_bookFlowLayout) {
        _bookFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _bookFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _bookFlowLayout;
}

- (UICollectionView *)bookCollectionView{
    if (!_bookCollectionView) {
        _bookCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, self.videoCollectionView.frame.size.height) collectionViewLayout:self.bookFlowLayout];
        _bookCollectionView.delegate = self;
        _bookCollectionView.dataSource = self;
        _bookCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_bookCollectionView registerClass:[BookCollectionViewCell class] forCellWithReuseIdentifier:@"bookCell"];
    }
    return _bookCollectionView;
}

- (UIImageView *)hLine{
    if (!_hLine) {
        _hLine = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W / 3 - WidthScale(30)) / 2, 64 + HeightScale(44) - HeightScale(2), WidthScale(30), HeightScale(2))];
        _hLine.image =ImageNamed(@"liulanlishi_xian");
    }
    return _hLine;
}

- (UIImageView *)vLine{
    if (!_vLine) {
        _vLine = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - 2) / 3, 64 + HeightScale(10), 1, HeightScale(24))];
        _vLine.image = ImageNamed(@"liulanlishifenge");
    }
    return _vLine;
}

- (UIButton *)videoButton{
    if (!_videoButton) {
        _videoButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W / 3 * 2, 64, SCREEN_W / 3, HeightScale(44))];
        [_videoButton setTitle:@"视频" forState:UIControlStateNormal];
        [_videoButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_videoButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _videoButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_videoButton initWithBlock:^(id obj) {
            DLog(@"视频");
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.backScrollView.contentOffset = CGPointMake(SCREEN_W * 2, 0);
                weakSelf.hLine.center = CGPointMake(weakSelf.backScrollView.contentOffset.x / 3 + SCREEN_W / 6, weakSelf.hLine.center.y);
            }];
            
        } for:UIControlEventTouchUpInside];
    }
    return _videoButton;
}

- (UIButton *)bookButton{
    if (!_bookButton) {
        _bookButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W / 3, HeightScale(44))];
        [_bookButton setTitle:@"电子书" forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _bookButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_bookButton initWithBlock:^(id obj) {
            DLog(@"电子书");
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.backScrollView.contentOffset = CGPointMake(0, 0);
                weakSelf.hLine.center = CGPointMake(weakSelf.backScrollView.contentOffset.x / 3 + SCREEN_W / 6, weakSelf.hLine.center.y);
            }];
            
        } for:UIControlEventTouchUpInside];
    }
    return _bookButton;
}

- (UIScrollView *)backScrollView{
    if (!_backScrollView) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64 + HeightScale(44), SCREEN_W, SCREEN_H - 64 - HeightScale(44))];
        _backScrollView.contentSize = CGSizeMake(SCREEN_W * 3, _backScrollView.frame.size.height);
        _backScrollView.pagingEnabled = YES;
        _backScrollView.delegate = self;
        _backScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _backScrollView;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

#pragma mark - lify cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"浏览历史";
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.bookButton];
    
    [self.view addSubview:self.magazineButton];
    
    [self.view addSubview:self.videoButton];
    
    [self.view addSubview:self.hLine];
    
    [self.view addSubview:self.vLine];
    
    [self.view addSubview:self.vLine2];
    
    [self.view addSubview:self.backScrollView];
    
    [self.backScrollView addSubview:self.videoCollectionView];
    
    [self.backScrollView addSubview:self.magazineCollectionView];
    
    [self.backScrollView addSubview:self.bookCollectionView];
    
    [self requestHistoryOfBook];
    
    [self requestHistoryOfMagazine];
    
    [self requestHistoryOfVideo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - MPMoviePlayerPlaybackDidFinishNotification Method

- (void)videoFinished{
    DLog(@"停止播放");
    if (self.player) {
        self.player = nil;
    }
}

- (void)noMoreVideos{
    
    for (UIView *subView in self.player.view.subviews) {
        DLog(@"%@", subView);
        for (UIView *subview in subView.subviews) {
            DLog(@"subView %@", subview);
            for (UIView *subView2 in subview.subviews) {
                for (UIView *subview3 in subView2.subviews) {
                    for (UIView *subview4 in subview3.subviews) {
                        for (UIView *subview5 in subview4.subviews) {
                            if ([subview5 isKindOfClass:[UIButton class]]) {
                                DLog(@"%@", subview5);
                                if (subview5.frame.size.width == 32) {
                                    UIButton *button = (UIButton *)subview5;
                                    [button removeTarget:nil
                                                  action:NULL
                                        forControlEvents:UIControlEventAllEvents];
                                    [button initWithBlock:^(id obj) {
                                        [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
                                    } for:UIControlEventTouchUpInside];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - UICollectionDelegate & UICollectionViewDataSource Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.bookCollectionView]) {
        return self.bookArr.count;
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        return self.magazineArr.count;
    } else {
        return self.videoArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.videoCollectionView]) {
        SubVideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"videoCell" forIndexPath:indexPath];
        cell.titleLabel.text = [NSString stringWithFormat:@"【%@】", self.videoArr[indexPath.row][@"name"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershipin")];
        return cell;
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        MagazineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"magazineCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.magazineArr[indexPath.row][@"name"];
        cell.authorLabel.text = self.magazineArr[indexPath.row][@"issuename"];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.magazineArr[indexPath.row][@"coverimgpath"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        return cell;
    } else {
        BookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bookCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.bookArr[indexPath.row][@"name"];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.bookArr[indexPath.row][@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        cell.authorLabel.text = self.bookArr[indexPath.row][@"author"];
        return cell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.videoCollectionView]) {
        return CGSizeMake(WidthScale(190), HeightScale(144));
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        return CGSizeMake(WidthScale(100), HeightScale(190));
    } else{
        return CGSizeMake(WidthScale(100), HeightScale(190));
    }
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.videoCollectionView]) {
        return WidthScale(10);
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        return WidthScale(10);
    } else {
        return WidthScale(10);
    }
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.videoCollectionView]) {
        return HeightScale(25);
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        return HeightScale(10);
    } else {
        return HeightScale(10);
    }
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.videoCollectionView]) {
        return UIEdgeInsetsMake(HeightScale(20), WidthScale(10), HeightScale(20), WidthScale(10));
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        return UIEdgeInsetsMake(HeightScale(20), WidthScale(20), HeightScale(20), WidthScale(20));
    } else {
        return UIEdgeInsetsMake(HeightScale(20), WidthScale(20), HeightScale(20), WidthScale(20));
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.bookCollectionView]) {
        //电子书
        BookDetailViewController *bookDetailVC = [[BookDetailViewController alloc] init];
        bookDetailVC.bookDic = self.bookArr[indexPath.row];
        [self.navigationController pushViewController:bookDetailVC animated:YES];
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        //期刊
        MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
        magazineDetailVC.magazineDic = self.magazineArr[indexPath.row];
        [self.navigationController pushViewController:magazineDetailVC animated:YES];
    } else {
        //视频
        
        DLog(@"播放视频");
        if ([self.videoArr[indexPath.row][@"filepath"] isKindOfClass:[NSNull class]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        } else {
            NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"filePath"]];
            self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
            [self presentViewController:self.player animated:YES completion:^{
                [self requestStatistics:indexPath ID:self.videoArr[indexPath.row][@"id"]];
                [self noMoreVideos];
            }];
        }

        
    }
}

#pragma mark - UIScrollViewDelegate Method

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.backScrollView]) {
        self.hLine.center = CGPointMake(scrollView.contentOffset.x / 3 + SCREEN_W / 6, self.hLine.center.y);
        
        if (scrollView.contentOffset.x < - 50) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - data request

/** 获取浏览历史（书籍） */
- (void)requestHistoryOfBook{
    NSString *URL = [NSString stringWithFormat:KgetHistory, KHostAddress, @(1), KOrganizationID, [AppDelegate shareDelegate].userModel.userId, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取书籍浏览历史成功");
            
            self.bookArr = [NSMutableArray arrayWithArray:responseObject[@"data"][@"items"]];
            
            
            //数组去重
            NSMutableArray *listAry = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in self.bookArr) {
                if (![listAry containsObject:dic]) {
                    [listAry addObject:dic];
                }
            }
            
            [self.bookArr removeAllObjects];
            
            [self.bookArr addObjectsFromArray:listAry];
            
            [self.bookCollectionView reloadData];
        }
    
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 获取浏览历史（期刊） */
- (void)requestHistoryOfMagazine{
    NSString *URL = [NSString stringWithFormat:KgetHistory, KHostAddress, @(4), KOrganizationID, [AppDelegate shareDelegate].userModel.userId, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取期刊浏览历史成功");
            
            self.magazineArr = [NSMutableArray arrayWithArray:responseObject[@"data"][@"items"]];
            
            
            //数组去重
            NSMutableArray *listAry = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in self.magazineArr) {
                if (![listAry containsObject:dic]) {
                    [listAry addObject:dic];
                }
            }
            
            [self.magazineArr removeAllObjects];
            
            [self.magazineArr addObjectsFromArray:listAry];
    
            [self.magazineCollectionView reloadData];
        }
        
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 获取浏览历史（视频） */
- (void)requestHistoryOfVideo{
    NSString *URL = [NSString stringWithFormat:KgetHistory, KHostAddress, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取视频浏览历史成功");
            
            self.videoArr = [NSMutableArray arrayWithArray:responseObject[@"data"][@"items"]];
            
            
            //数组去重
            NSMutableArray *listAry = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in self.videoArr) {
                if (![listAry containsObject:dic]) {
                    [listAry addObject:dic];
                }
            }
            
            [self.videoArr removeAllObjects];
            
            [self.videoArr addObjectsFromArray:listAry];
            
            [self.videoCollectionView reloadData];
        }
        
    } failure:^(NSError *error) {
        DLog(@"浏览历史：视频 %@", error);
    }];
}

/** 添加统计 */
- (void)requestStatistics:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(2), ID];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

@end
